﻿using BotDetector.Core.Model;

namespace BotDetector.Core.Detector
{
    public class BotDetector : IBotDetector
    {
        private BotDetectorConfigurator configurator = new BotDetectorConfigurator();
        private ExactPhraseAnalyzor exactPhraseAnalyzor;

        public bool IsBot(ResultItemList resultItemList)
        {
            const char quote = '"';
            const char emptyChar = '\0';
            string phrase = resultItemList.Phrase.Replace(quote, emptyChar);
            BotLength typeOfLength = DetectLength(phrase);
            if (typeOfLength == BotLength.TooShort 
                || CheckIfSong(resultItemList))
            {
                return false;
            }

            exactPhraseAnalyzor = new ExactPhraseAnalyzor(typeOfLength);
            return exactPhraseAnalyzor.AnalyzeAfterExactPhrase(resultItemList);
        }
        public bool CheckIfSong(ResultItemList resultItemList)
        {
            int k = 0;
            foreach (ResultItem resultItem in resultItemList)
            {
                if (CheckIfContainsSongKeyWords(resultItem))
                {
                    k++;
                }
            }

            if (k > 2)
            {
                return true;
            }
            return false;
        }
        private bool CheckIfContainsSongKeyWords(ResultItem resultItem)
        {
            string youtubeURL = "www.youtube.com";
            string lyricsEN = "lyrics";
            string lyricsRO = "versuri";
            return (resultItem.Url.Contains(youtubeURL)
                || resultItem.Title.Contains(lyricsEN)
                || resultItem.Title.Contains(lyricsRO));
        }
        public BotLength DetectLength(string phrase)
        {
            string[] words = phrase.Split(' ');
            if (words.Length <= configurator.tooShortValue)
            {
                return BotLength.TooShort;
            }
            if (words.Length <= configurator.shortValue)
            {
                return BotLength.Short;
            }
            if (words.Length <= configurator.mediumValue)
            {
                return BotLength.Medium;
            }
            return BotLength.Long;
        }
    }
}
